package com.primary.controller;

import com.primary.common.CommonStr;
import com.primary.common.HttpCode;
import com.primary.common.MsgCode;
import com.primary.common.Result;
import com.primary.entity.Users;
import com.primary.service.UsersService;
import com.primary.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ResourceBundle;

/**
 * @author Shen Jianhui
 * @date 2023/6/18 Sunday
 */

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
    //原本的写法会带来额外的开销，这种写法能使得配置文件只加载一次
    private static final ResourceBundle bundle;

    static {
        bundle = ResourceBundle.getBundle("config/log_message");
//        bundle = ResourceBundle.getBundle("config\\log_message");
    }
//    ResourceBundle bundle = ResourceBundle.getBundle("config\\log_message");
    @Autowired
    UsersService usersService;

    /**
     * @author Shen Jianhui
     * @description Providing a method to log in the system.
     * @param users
     * @return The System Code and message about information of logging in.
     */
    @RequestMapping(value = "/nameandpwd",method = {RequestMethod.POST})
    public Result loginByNameAndPwd(@RequestBody Users users) {
        Users user = usersService.getUserByNameAndPassword(users.getName(), users.getPassword());
        if (null != user) {
            // 20240421 Shen Jianhui 如果账户被禁用，那么此用户不能登录系统 Added STATR
            if(CommonStr.ZERO.equals(user.getStatus())){
                return Result.error(HttpCode.HTTP_MINUS_ONE, bundle.getString(MsgCode.MSG10002));
            }
            // 20240421 Shen Jianhui 如果账户被禁用，那么此用户不能登录系统 Added END
            if(!(CommonStr.ZERO.equals(user.getUserType())) && !(CommonStr.ONE.equals(user.getUserType()))){
                return Result.error(HttpCode.HTTP_MINUS_FIVE, bundle.getString(MsgCode.MSG10004));
            }
            String token= JwtUtils.generateToken(users.getName());
            return Result.success(user);
        } else {
            return Result.error(bundle.getString(MsgCode.MSG10001));
        }
    }
}
